#!/usr/bin/python3
import os
import re
import sys

product_path = '/keyicx/python'

argv = ''
if len(sys.argv) > 1:
    argv = sys.argv[1]

def get_ip_address():
    restr = r'inet\s+([\d+\.]+)\s+'

    ipadd = ''

    wlanip = os.popen('ifconfig wlan0').read()
    matc = re.search( restr, wlanip, re.M|re.I )
    if matc!=None:
        ipadd = str(matc.group(1))

    eth0ip = os.popen('ifconfig eth0').read()
    matc = re.search( restr, eth0ip, re.M|re.I )
    if matc!=None:
        ipadd = str(matc.group(1))

    print(ipadd)

def debug_mode(isopen = True):
    mode_str = ''
    if isopen:
        mode_str = 'Logging:\n  Level: DEBUG          #'
    else:
        mode_str = 'Logging:\n  Level: WARNING        #'

    logfile = os.path.join(product_path, 'config.yaml')
    if os.path.isfile(logfile) is False:
        print("NOFILE")
    else:
        f = open(logfile,"r")
        fstr = f.read()
        f.close()

        restr = r'Logging:\n+\s+Level:\s*(\w+)\s+#{1}'
        math  = re.search(restr, fstr, flags=re.M|re.I)
        if math != None:
            fstr = re.sub(restr, mode_str, fstr, 1, re.M|re.I )
            fo = open(logfile, "w+")
            fo.write(fstr)
            fo.close()
            print("OK")
        else:
            print("ERROR")

# 启用root用户登录
if argv=='getip':
    get_ip_address()

# 启用root用户登录
elif argv=='setroot':
    ssh_file = '/etc/ssh/sshd_config'
    f = open(ssh_file,"r")
    fstr = f.read()
    f.close()

    is_write = False
    restr = r'^#?Port\s\d+\n'
    math = re.search(restr, fstr, flags=re.M|re.I )
    if math != None:
        fstr = re.sub(restr, 'Port 21232\n', fstr, flags=re.M|re.I )
        is_write = True

    restr = r'^#?PermitRootLogin\s+.+\n'
    math = re.search(restr, fstr, flags=re.M|re.I )
    if math != None:
        fstr = re.sub(restr, 'PermitRootLogin yes\n', fstr, flags=re.M|re.I )
        is_write = True

    if is_write:
        fo = open(ssh_file, "w+")
        fo.write(fstr)
        fo.close()
        print("OK")
    else:
        print("ERROR")


# 打开打印日志
elif argv=='openlog':
    debug_mode(True)

# 关闭打印日志
elif argv=='closelog':
    debug_mode(False)